package com.sinodata.bsm.cicp.collector.windows.snmp;

import java.io.IOException;
import java.util.List;

import org.snmp4j.CommunityTarget;
import org.snmp4j.Snmp;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OctetString;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.ProtocolParameterUtil;
import com.sinodata.bsm.common.constants.SnmpConstants;
import com.sinodata.bsm.common.vo.ProtocolParameter;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangpeng
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-8-27 下午5:17:36          wangpeng        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public abstract class SnmpCollector extends Collector {

    protected String ip;

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        setIp(ip);
        ProtocolParameter parameter = ProtocolParameterUtil.getSnmpValue(ip);

        CommunityTarget target = new CommunityTarget();
        if (parameter == null) {
            target.setCommunity(new OctetString("public"));
            target.setAddress(GenericAddress.parse("udp:" + ip.trim() + "/161"));
            target.setRetries(0);
            target.setTimeout(5000);
            target.setVersion(SnmpConstants.getVersion(SnmpConstants.FIRST_VERSION_STR));
        } else {
            target.setCommunity(new OctetString(parameter.getUserName()));
            Address localAddress = GenericAddress.parse("udp:" + ip.trim() + "/" + parameter.getPort());
            target.setAddress(localAddress);
            target.setRetries(0);
            target.setTimeout(5000);
            target.setVersion(SnmpConstants.getVersion(parameter.getProtocol()));
        }

        Snmp snmp = null;
        try {
            snmp = new Snmp(new DefaultUdpTransportMapping());
            snmp.listen();
            return collect(snmp, target);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (snmp != null) {
                try {
                    snmp.close();
                } catch (Exception e2) {
                }
            }
        }

    }

    public abstract List<ResPropertyValue> collect(Snmp snmp, CommunityTarget target) throws CollectorException;

    private void setIp(String ip) {
        this.ip = ip;
    }
}
